# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     run
   Description :
   Author :       潘晓华
   date：          2018/7/23
-------------------------------------------------
"""


from openshiftx.pod import Pod
from prometheus_client import start_http_server, Gauge
from time import sleep

restart_labels = []

router_count_gauge = Gauge('router_pod_ready_count', 'Ready Router Pod Count')
registry_count_gauge = Gauge('registry_pod_ready_count', 'Ready Registry Pod Count')
restart_count_gauge = Gauge('pod_restart_count_up_to_10', 'Amount Of Pod Restart Count > 10', ['pod_name', 'project_name'])

def process_request():
    try:
        router_count_gauge.set(len(Pod.get_ready_pods_by_selector(project='default', selector='deploymentconfig=router')))
        registry_count_gauge.set(len(Pod.get_ready_pods_by_selector(project='default', selector='deploymentconfig=docker-registry')))
        set_pod_restart_monitor()
    except Exception as e:
        print(e.message)


def set_pod_restart_monitor():
    global restart_labels
    pods_data = Pod.get_all()
    for label in restart_labels:
        restart_count_gauge.remove(label[0], label[1])
    restart_labels = []
    for pod in pods_data['items']:
        pod_name = pod['metadata']['name']
        project_name = pod['metadata']['namespace']
        restart_count = pod['status']['containerStatuses'][0]['restartCount']
        if restart_count > 10:
            restart_count_gauge.labels(pod_name, project_name).set(restart_count)
            restart_labels.append((pod_name, project_name))

if __name__ == '__main__':
    start_http_server(9688, '0.0.0.0')
    while True:
        sleep(5)
        process_request()